package com.advice;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

public class AroundService implements MethodInterceptor {
    /**
     * around增强 环绕正确 相当于 前置，后置，异常抛出增强合一
     * @param methodInvocation
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        System.out.println("============环绕增强开始================");
        Date start = new Date();
        Object target = methodInvocation.getClass(); //目标方法所在类
        System.out.println("目标方法所在类是："+target);
        Method method = methodInvocation.getMethod(); //目标方法
        System.out.println("目标方法名是："+method.getName());
        Object[] args = methodInvocation.getArguments(); //目标方法参数
        System.out.println("目标方法参数是："+ Arrays.toString(args));
        try {
            System.out.println("目标方法执行前");
            Object result = methodInvocation.proceed(); //执行目标方法
            System.out.println("目标方法执行后");
            System.out.println("目标方法返回值是："+result);
            Date end = new Date();
            System.out.println("===========环绕增强结束=============");
            System.out.println("方法执行时间："+(end.getTime()-start.getTime()));
            return result;
        } catch (Exception e) {
            System.out.println("目标方法执行异常--环绕增强捕获异常");
            throw e;
        }
    }
}
